package com.affablebeans.cart;

import java.util.ArrayList;
import java.util.List;

import com.affablebeans.model.entity.Product;

/**
 * 
 * @author Bora SAYINER
 * @since Jan 31, 2015 6:38:49 PM
 * @version 1.0.0
 */
public class ShoppingCart {

	private double total;
	private int numberOfItem;

	private final List<ShoppingItem> items;

	public ShoppingCart() {
		this.items = new ArrayList<ShoppingItem>();
		this.total = 0;
		this.numberOfItem = 0;
	}

	public void addProduct(Product product) {
		boolean isNewItem = true;
		for (ShoppingItem shoppingItem : items) {
			if (product.equals(shoppingItem.getProduct())) {
				isNewItem = false;
				shoppingItem.incrementQuantity();
				break;
			}
		}
		if (isNewItem) {
			ShoppingItem shoppingItem = new ShoppingItem(product);
			items.add(shoppingItem);
		}
	}

	public void updateProduct(Product product, int quantity) {
		for (ShoppingItem shoppingItem : items) {
			if (shoppingItem.getProduct().equals(product)) {
				if (quantity == 0) {
					items.remove(product);
				} else {
					shoppingItem.setQuantity(quantity);
				}
			}
		}
	}

	public List<ShoppingItem> getItems() {
		return items;
	}

	public int getNumberOfItem() {
		numberOfItem = 0;
		for (ShoppingItem shoppingItem : items) {
			numberOfItem += shoppingItem.getQuantity();
		}
		return numberOfItem;
	}

	public double getTotal() {
		total = 0;
		for (ShoppingItem shoppingItem : items) {
			total += shoppingItem.getTotal();
		}
		return total;
	}

	public void clear() {
		items.clear();
		total = 0;
		numberOfItem = 0;
	}

}
